package MyApp::Controller::Selenium;
use Mojo::Base 'Mojolicious::Controller';
use Mojo::JSON qw(decode_json encode_json);
use MyApp::Model::Vpnxml;
use Selenium::Remote::Driver;
use Selenium::Firefox::Profile;

sub auto_operation {
    my $self = shift;


    #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    #$self->res->headers->access_control_allow_origin('*');    #测试代码，上线前删除
    #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    
    #全局修改参数：
    my $download_dir = '/home/dahama/selenium';
    my $firefox_proflies_dir = '/home/dahama/selenium/myconfigure';
    
    
    
    my $export_file = "$download_dir/ive-export.xml";
    my $import_file = "$download_dir/import.xml";

    #自动下载文件：
    my $profile = Selenium::Firefox::Profile->new(
        'profile_dir' => $firefox_proflies_dir );

    $profile->set_preference( 'browser.download.folderList' => 2 );
    $profile->set_preference( 'browser.download.dir' => $download_dir );
    $profile->set_preference(
        'browser.helperApps.neverAsk.saveToDisk' => 'text/xml' );

    my $driver = Selenium::Remote::Driver->new(
        browser_name    => "firefox",
        firefox_profile => $profile
    );

    $driver->get('https://vpn.dahama.com.cn/guanliduankongzhitai');
    my $element = $driver->find_element_by_id('username');
    $element->send_keys('dahama');

    $element = $driver->find_element_by_id('password');
    $element->send_keys('xxxxxxxxxxxxxxxxxx');

    $element = $driver->find_element_by_id('btnSubmit_6');
    $element->click();

    if ( $driver->get_current_url() =~ /p=admin-confirm&id=/ ) {
        my $continue_element = $driver->find_element_by_name('btnContinue');
        $continue_element->click();
    }

    $element = $driver->find_element_by_link_text('Import/Export');
    $element->click();

    $element = $driver->find_element_by_link_text('XML Import/Export');
    $element->click();

    $element = $driver->find_element_by_id('arrowEndpoint');
    $element->click();

    my $option_element = $driver->find_element_by_id('optHCAll');
    $option_element->click();

    $element = $driver->find_element_by_id('arrowLocalUsers');
    $element->click();

    $option_element = $driver->find_element_by_id('optLocalUsersAll');
    $option_element->click();

    $option_element = $driver->find_element_by_id('action_6');
    $option_element->click();

    sleep(10);

    $driver->quit();

    #处理文件

    my $db = $self->mysql->db;

    return $self->render( json => { success => 0 } ) unless -e $export_file;

    open my $FILE, "<", $export_file
      or die "Can not open the file:$!\n";

    my $right;
    while ( my $line = <$FILE> ) {
        chomp $line;
        $right = 1 if $line =~ /xml\.juniper\.net/;
    }
    close $FILE;

    return $self->render( json => { success => 0 } ) unless $right == 1;

    my $xml = MyApp::Model::Vpnxml->new($export_file);

    my $addmacs =
      $db->query('select mac from mac_dealing where operation=1')->arrays;
    my $delmacs =
      $db->query('select mac from mac_dealing where operation=0')->arrays;

    my $addaccount = $db->query(
'select username,company_name,password from account_dealing where operation=1'
    )->hashes;
    my $delaccount =
      $db->query('select username from account_dealing where operation=0')
      ->arrays;

    if ($addmacs) {
        #my $testaddmacs = join ',',@$addmacs;
        #open my $FILE,">>",'Dealfiles/test.txt' or die "Can't open the file: $!\n";
        #print $FILE $testaddmacs;
        #close $FILE;
        $xml->addmacaddress($addmacs);
    }

    if ($delmacs) {
        $xml->deletemacaddress($delmacs);
    }

    if ($delaccount) {
        for my $account (@$delaccount) {
            $account = $account->[0];
            $xml->deleteuser($account);
        }
    }

    if ($addaccount) {
        foreach my $hash (@$addaccount) {
            my $company_id =
              $db->query( 'select id from companylist where name=?',
                $hash->{company_name} )->array->[0];
            my $role = $db->query(
                'select role from sbu_company_relation where company_id=?',
                $company_id )->array->[0];
            my $group;

            if ( $role =~ /001/ ) {
                $group = 'DAHAMA';
            }
            elsif ( $role =~ /00[12]/ ) {
                $group = 'Dealer';
            }
            else {
                $group = 'supplier';
            }

            $xml->createuser( $group, $hash->{username}, $hash->{password},
                $hash->{company_name} );
        }
    }

    $xml->out($import_file);

    my $mac_del_db = $db->query('select * from mac_dealing')->hashes;

    my $account_del_db = $db->query('select * from account_dealing')->hashes;

    #存储将要删除的数据库记录
    open my $HISFILE, ">>", "Dealfiles/History.txt"
      or die "Can't open the file:$!\n";

    for my $hash (@$mac_del_db) {
        print $HISFILE "$hash->{mac},$hash->{operation}\n";
		if ($hash->{operation} =~ /0/) {
			$db->query('delete from maclist where mac=?',$hash->{mac});
		}
    }
    for my $hash (@$account_del_db) {
        print $HISFILE "$hash->{username},$hash->{password},$hash->{company_name},$hash->{operation}\n";
		if ($hash->{operation} =~ /0/) {
			$db->query('delete from vpn_account where username=?',$hash->{username});
		}
    }

    close $HISFILE;

    #删除两个处理表中的数据
    $db->query('delete from mac_dealing');
    $db->query('delete from account_dealing');

    #删除公司关系表
    $db->query('delete from sbu_company_relation where enable=0');

    return $self->render( json => { success => 0 } ) unless -e $import_file;
    #$self->render( json => { success => 1 } );

    #自动上传文档

    $driver = Selenium::Remote::Driver->new(
        browser_name    => "firefox",
        firefox_profile => $profile
    );

    $driver->get('https://vpn.dahama.com.cn/guanliduankongzhitai');
    my $element = $driver->find_element_by_id('username');
    $element->send_keys('dahama');

    $element = $driver->find_element_by_id('password');
    $element->send_keys('xxxxxxxxxxxxxxxxxx');

    $element = $driver->find_element_by_id('btnSubmit_6');
    $element->click();

    if ( $driver->get_current_url() =~ /p=admin-confirm&id=/ ) {
        my $continue_element = $driver->find_element_by_name('btnContinue');
        $continue_element->click();
    }

    $element = $driver->find_element_by_link_text('Import/Export');
    $element->click();

    $element = $driver->find_element_by_link_text('XML Import/Export');
    $element->click();

    $element = $driver->find_element_by_link_text('Import');
    $element->click();

    my $remote_fname = $driver->upload_file($import_file);
    $element = $driver->find_element_by_id('xml_roles_and_policies');
    $element->send_keys($remote_fname);

    $option_element = $driver->find_element_by_id('action_7');
    $option_element->click();

    do {
        sleep(2);
    } while ( !$driver->find_element_by_id('table_xml-errors_1') );

    $driver->quit();

    unlink($export_file);
    unlink($import_file);

    return $self->render( json => { success => 1 } );

}

1;
